package com.mangix.utils;

import com.mangix.conf.MangixConfig;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Ahan on 2014/5/13.
 */
public class MangixUtils {

    public static long hash(String string, int m) {
        byte[] bytesOfString = string.getBytes();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] theDigest = md.digest(bytesOfString);
            long hashResult = bytesToLong(theDigest);
            hashResult = hashResult & ((1 << m) - 1);
            return hashResult;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return string.hashCode() % (2 ^ m);
        }

    }

    private static long bytesToLong(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE);
        buffer.put(bytes);
        buffer.flip();//need flip
        return buffer.getLong();
    }

    public static void main(String[] args) throws IOException {
        MangixConfig config = MangixConfig.getInstance();
        System.out.println(config.getM());
        System.out.println(isIDInInterval(18, 7, 18, true, false, config.getM()));
        System.out.println(hash("192.168.56.111:8097", config.getM()));
        System.out.println(hash("192.168.56.160:8087", config.getM()));
        System.out.println(hash("192.168.56.111:8093", config.getM()));
        System.out.println(hash("192.168.56.160:8086", config.getM()));
        System.out.println(hash("192.168.56.111:8099", config.getM()));
        System.out.println(hash("10.22.13.77:8090", config.getM()));
        System.out.println(hash("10.22.13.77:8091", config.getM()));
    }

    public static boolean isIDInInterval(long id, long start, long end, boolean startEqual, boolean endEqual, int m) {
        int ringSize = (int) Math.pow(2, m);
        if ((startEqual && id == start) || (endEqual && id == end)) {
            return true;
        } else if (start < end) {
            if (start < id && id < end)
                return true;
            return false;
        } else if (start >= end) {
            if (id > start && id < end + ringSize) {
                return true;
            } else if (id < start && id < end) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
